'use strict';

var querystring = require('querystring');

var crypto = require('crypto');

var fs = require('fs');

module.exports = {
    Format: dateFormat,
    rsaSign: rsaSign,
    assignArray: assignArray,
    buildSign: _buildSign
};

function dateFormat(format) {
    //格式化时间参数

    if (!format) {
        format = "yyyy-MM-dd hh:mm:ss"
    }
    Date.prototype.Format = Format;

    return new Date().Format(format);
}

function Format(fmt) {
    var o = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S": this.getMilliseconds()
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

function rsaSign(json, private_key) {

    if (!private_key) {
        throw new Error('missing private key');
    }

    var Pkey = fs.readFileSync(private_key);

    var keys = Object.keys(json);
    keys = keys.sort();
    var map = {};
    for (var i = 0; i < keys.length; i++) {
        var key = keys[i];
        if (key !== 'sign' && key !== 'sign_type' && json[key]) {
            map[key] = json[key];
        }
    }
    var str = querystring.unescape(querystring.stringify(map));

    var signer = crypto.createSign('RSA-SHA1');

    signer.update(str);

    var sign = signer.sign(Pkey, 'base64');

    return sign;
}

function assignArray(me, json) {
    for (var key in json) {
        if (json.hasOwnProperty(key)) {
            me[key] = json[key];
        }
    }
}

function _buildSign(json) {
    var keys = Object.keys(json);
    keys = keys.sort();
    var map = {};

    var aliKey = json['key'];
    for (var i = 0; i < keys.length; i++) {
        var key = keys[i];
        if (key !== 'sign' && key !== 'sign_type' && json[key]) {
            map[key] = json[key];
        }
    }

    var str = querystring.unescape(querystring.stringify(map)) + aliKey;

    return crypto.createHash('md5').update(str, 'utf-8').digest('hex');
}
